import request from "@/utils/request";
import axios from "axios";
import { marked } from "marked";

export const getPostList = async (pageNum = 1, pageSize = 5) => {
  let postList: PostData[] = [];
  for (let i = 0; i < pageSize; i++) {
    const data = await axios.get(`http://localhost:5173/md/lol_${i + 1}.md`);
    let md = await marked.parse(data.data);
    let jsonPattern =
      /<pre><code class="language-json">([\s\S]*?)<\/code><\/pre>/;
    const matchResult = md.match(jsonPattern);
    if (matchResult) {
      const jsonStr = matchResult[1].replace(/&quot;/g, '"');
      const jsonData = JSON.parse(jsonStr);
      postList.push(jsonData);
    }
  }
  postList = postList.sort((a, b) => {
    const date1 = new Date(a.date);
    const date2 = new Date(b.date);
    return date2.getTime() - date1.getTime();
  });
  return postList;
};

export const getCommunityList = (pageNum = 1, pageSize = 10) => {
  return request.post("/post/list", {
    pageNum,
    pageSize,
  });
};

export const getCommunity = (id: number) => {
  return request.get("/post/one", {
    params: {
      id: id,
    },
  });
};

export const getUserPostList = () => {
  return request.get("/post/user");
};

export const uploadCommunity = (data: CommunityData) => {
  return request.post("/post/publish", data);
};
